#!/usr/bin/python
import urllib2, re, sys

SHIPPING = 3.99

def price(isbn):
    try:
        url = ('http://www.amazon.com/s/ref=nb_sb_noss?'+
               'url=search-alias%3Daps&field-keywords='+isbn)
        f = urllib2.urlopen(url, timeout=5)
        lines = [l for l in f]
        f.close()

        for l in lines:
            m = re.search(r'span class\="price bld\"\>\$(\d+\.\d+)\<', l)
            if m and l.find('used')>=0:
                return float(m.group(1)) + SHIPPING
        return None
    except:
        return None

def main():
    for l in sys.stdin:
        isbn = l.strip()
        print '%s\t%s' % (isbn, str(price(isbn)))

# ./get_amazon_price.py 9781118752142 9780137832347 9780226307800 9781585100194 9780132737715 9781439046944 9780767923057 9780395924990 9780743247542 9780073513171

if __name__ == '__main__':
    main()
